package com.boss.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boss.entity.FileInfo;
import com.boss.service.FileInfoService;
import com.boss.util.ResultVOUtil;
import com.boss.vo.ResultVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    private static final String baseUrl = "http://localhost:3000";
    @Resource
    private FileInfoService fileInfoService;
    @PostMapping("/upload")
    public ResultVO upload(MultipartFile file,String username) throws IOException {
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        String flag = IdUtil.fastSimpleUUID();//通过Hutool工具包的IdUtil类获取uuid作为前缀
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + filename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);//使用Hutool工具包将我们接收到文件保存到rootFilePath中
        QueryWrapper<FileInfo> wrapper = new QueryWrapper<>();
        wrapper.like("title", filename).like("username", username);
        if(fileInfoService.count(wrapper)!=0&&!username.equals("")){
            System.out.println(fileInfoService.count(wrapper));
            System.out.println("usename: "+username+"  filename: "+filename);
            System.out.println("文件已存在");
            return ResultVOUtil.fail();
        }else{
            FileInfo fileInfo = new FileInfo();
            fileInfo.setTitle(filename);
            fileInfo.setUploadDate(String.valueOf(new DateTime(new Date())));
            fileInfo.setImageName(flag);
            fileInfo.setUsername(username);
            boolean save = fileInfoService.save(fileInfo);
            System.out.println("文件保存结果：" + save);
        }
        return ResultVOUtil.success(baseUrl + "/file/download/" + flag);
    }

    @GetMapping("/download/{flag}")
    public ResultVO downloadFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;//新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/"; //定义文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);//通过文件的路径读取文件字节流
                os = response.getOutputStream();//通过response的输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
                return ResultVOUtil.success("文件下载成功");
            }
            else{
                return ResultVOUtil.success("文件不存在");
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
            return ResultVOUtil.success("文件下载失败");
        }
    }
    @GetMapping("/user")
    public ResultVO getUserImage(String username){
        QueryWrapper<FileInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        List<FileInfo> list = fileInfoService.list(wrapper);
        return ResultVOUtil.success(list);
    }

    @GetMapping ("/delete")
    public ResultVO deleteUserImage(String username,String imageName){
        System.out.println(username+imageName);
        QueryWrapper<FileInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username).eq("image_name",imageName);
        if(fileInfoService.count(wrapper)==0){
            return ResultVOUtil.success("删除失败,不存在该文件");
        }
        boolean remove = fileInfoService.remove(wrapper);
        if(remove){
            return ResultVOUtil.success("删除成功");
        }
        else{
            return ResultVOUtil.success("删除失败");
        }
    }
}
